package com.ape.mapsa.api.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ape.mapsa.model.User;
import com.ape.mapsa.service.IUserService;

@Service
@Path("/users/")
public class UserEndpoint {

	private static final Logger logger = Logger.getLogger(UserEndpoint.class);

	@Context
	SecurityContext sc;
	@Context
	HttpHeaders request;

	@Autowired
	IUserService userService;

	@POST
	@Path("/login")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public Response idbases(@FormParam("username") String username, @FormParam("password") String password) {
		logger.debug("Username: " + username);
		logger.debug("Password: " + password);

		User loginUser = userService.getUserByEmail(username);
		if (loginUser != null && loginUser.getPassword().equals(password)) {
			logger.debug("Loggedin");
			User user = new User();
			user.setUserName(loginUser.getUserName());
			user.setEmail(loginUser.getEmail());
			user.setFirstName(loginUser.getFirstName());
			return Response.ok(user, MediaType.APPLICATION_JSON).build();
		} else {
			logger.debug("Not authorized");
			String result = "NOOOOOOTTTTTTT";
			return Response.status(Status.UNAUTHORIZED).entity(result).build();
		}
	}

	@GET
	@Path("/test")
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)
	public String idbases() {
		return "Testing";
	}

}
